package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.leaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * @author cxt
 * &#064;Description 自定义token工具类
 * &#064;create 2025/3/19 下午8:13
 */
public class JwtUtil {
//  token过期时间
    private static long tokenExpire = 60 * 60 * 1000L;
//  token密钥(里面的字符串就是自己设置的密码)
    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("D2JeCNcu5PSvAASFADW3RaSwnnbHWBAU".getBytes());

//  创建token方法
    public static String getToken(Long userId, String userName) {
        String token = Jwts.builder()
                .setSubject("USER_LOGIN")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpire))
                .claim("userId", userId)
                .claim("userName", userName)
                .signWith(tokenSignKey)
                .compact();
        return token;
    }

//  校验token的合法性
    public static Claims parseToken (String token) {
        if (token == null || "".equals(token)) {
            throw new leaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        try {
//          获取token校验器
            JwtParser build = Jwts.parserBuilder().setSigningKey(tokenSignKey).build();
//          读取token负载体
            Jws<Claims> claimsJws = build.parseClaimsJws(token);
            return claimsJws.getBody();
        }catch (ExpiredJwtException e) {
            throw new leaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){
            throw new leaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }

//  获取后端测试token 测试创建token是否正确
//    public static void main(String[] args) {
//        System.out.println(getToken(2L, "user"));
//    }
//  获取移动端测试token 测试创建token是否正确
      public static void main(String[] args) {
          System.out.println(getToken(8L, "15631275631"));
}
}
